package com.pengtu.web.project.labs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.Constants;
import com.pengtu.dao.HibernateUtils;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.Role;
import com.pengtu.entity.app.User;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.ServiceException;
import com.pengtu.service.app.AccountManager;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 * 
 * @author calvin
 */
// 定义URL映射对应/account/user.action
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({ @Result(name = BaseActionSupport.RELOAD, location = "/project/labs/userdepartment.action?organizationId=${organizationId}&projectId=${projectId}&typeId=${typeId}&deptId=${deptId}", type = "redirect") })
public class UserAction extends BaseActionSupport<User> {

	private static final long serialVersionUID = 8683878162525847072L;

	private AccountManager accountManager;

	// -- 页面属性 --//
	private String id;
	private User entity;
	private List<User> allUserList;
	private Page<User> page = new Page<User>(10);// 每页5条记录
	private List<String> checkedRoleIds; // 页面中钩选的角色id列表
	private String typeId;
	private String projectId;
	private String organizationId;
	private String deptId;
	private String userdeptId;

	// -- ModelDriven 与 Preparable函数 --//
	public void setId(String id) {
		this.id = id;
	}

	public User getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {

		if (StringUtils.isNotEmpty(id)) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
		}
	}

	public void prepare() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
		}
	}

	public String info() throws Exception {
		User user = SpringSecurityUtils.getCurrentUser();
		User myinfo = accountManager.getUser(user.getId());
		Struts2Utils.getRequest().setAttribute("user", myinfo);
		return Constants.INFO;
	}

	public String complete() throws Exception {
		return Constants.COMPLETE;
	}

	@Override
	public String list() throws Exception {
		// 设置默认排序方式
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = accountManager.findPageUser(page, queryfilter);
		return SUCCESS;
	}


	@Override
	public String input() throws Exception {
		if (StringUtils.isEmpty(id)) {

		} else {
			checkedRoleIds = entity.getRoleIds();
		}
		return INPUT;
	}

	public String view() throws Exception {
		if (StringUtils.isEmpty(id)) {

		} else {
			checkedRoleIds = entity.getRoleIds();
		}
		return VIEW;
	}

	@Override
	public String save() throws Exception {
		// 根据页面上的checkbox选择 整合User的Roles Set
		HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds,
				Role.class);
		accountManager.saveUser(entity);
		addActionMessage("保存用户成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			accountManager.deleteUser(id);
			addActionMessage("删除用户成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除用户失败");
		}
		return RELOAD;
	}

	// -- 其他Action函数 --//
	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newLoginName = request.getParameter("userName");
		String oldLoginName = request.getParameter("oldLoginName");

		if (accountManager.isLoginNameUnique(newLoginName, oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	/**
	 * 根据单位ID查询外部人员
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchForChoose() throws Exception {
		String orgId = Struts2Utils.getParameter("orgId");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<User> users = null;
		if (StringUtils.isNotEmpty(orgId)) {
			users = accountManager.findUsersByOrgId(orgId);
			for (User user : users) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", user.getId());
				map.put("userName", user.getUserName());
				map.put("name", user.getName());
				map.put("email", user.getEmail());
				map.put("mobilePhone", user.getMobilePhone());
				list.add(map);
			}
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return NONE;
	}

	/**
	 * 根据部门ID查询内部人员
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchChooseByDepId() throws Exception {
		String depId = Struts2Utils.getParameter("depId");
		List<User> users = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (StringUtils.isNotEmpty(depId)) {
			users = accountManager.searchUserByDepId(depId);
			for (User user : users) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", user.getId());
				map.put("userName", user.getUserName());
				map.put("name", user.getName());
				map.put("email", user.getEmail());
				map.put("mobilePhone", user.getMobilePhone());
				list.add(map);
			}
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return null;
	}

	// -- 页面属性访问函数 --//
	/**
	 * list页面显示用户分页列表.
	 */
	public Page<User> getPage() {
		return page;
	}

	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return accountManager.getAllRole();
	}

	/**
	 * input页面显示用户拥有的角色.
	 */
	public List<String> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	/**
	 * input页面提交用户拥有的角色.
	 */
	public void setCheckedRoleIds(List<String> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public List<User> getAllUserList() {
		return allUserList;
	}

	public String getTypeId() {
		return typeId;
	}

	public void setTypeId(String typeId) {
		this.typeId = typeId;
	}

	public String getProjectId() {
		return projectId;
	}

	public void setProjectId(String projectId) {
		this.projectId = projectId;
	}

	public String getOrganizationId() {
		return organizationId;
	}

	public void setOrganizationId(String organizationId) {
		this.organizationId = organizationId;
	}

	public String getDeptId() {
		return deptId;
	}

	public void setDeptId(String deptId) {
		this.deptId = deptId;
	}

	public String getUserdeptId() {
		return userdeptId;
	}

	public void setUserdeptId(String userdeptId) {
		this.userdeptId = userdeptId;
	}

}
